package handlers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"time"

	// "globalmap"

	"github.com/869413421/wechatbot/globalmap"
	"github.com/eatmoreapple/openwechat"
	// "gitee.com/lambertee/wechat-bot/globalmap"
)

var _ MessageHandlerInterface = (*GroupMessageHandler)(nil)

// GroupMessageHandler 群消息处理
type GroupMessageHandler struct {
}

// handle 处理消息
func (g *GroupMessageHandler) handle(msg *openwechat.Message) error {
	// if msg.IsText() {

	return g.ReplyText(msg)
	// }
	// return nil
}

// NewGroupMessageHandler 创建群消息处理器
func NewGroupMessageHandler() MessageHandlerInterface {
	return &GroupMessageHandler{}
}

// ReplyText 发送文本消息到群
func (g *GroupMessageHandler) ReplyText(msg *openwechat.Message) error {
	// 接收群消息
	sender, err := msg.Sender()
	group := openwechat.Group{sender}

	// 不是@的不处理
	// if !msg.IsAt() {
	// return nil
	// }

	// 替换掉@文本，然后向GPT发起请求
	// replaceText := "@" + sender.Self.NickName
	// requestText := strings.TrimSpace(strings.ReplaceAll(msg.Content, replaceText, ""))
	// reply, err := gtp.Completions(requestText)
	// if err != nil {
	// 	log.Printf("gtp request error: %v \n", err)
	// 	msg.ReplyText("机器人神了，我一会发现了就去修。")
	// 	return err
	// }
	// if reply == "" {
	// 	return nil
	// }

	// 获取@我的用户
	groupSender, err := msg.SenderInGroup()
	if err != nil {
		log.Printf("get sender in group error :%v \n", err)
		return err
	}
	username := groupSender.NickName
	userid := groupSender.ID()
	log.Printf("Received Group %v NickName %v Text Msg : %v", group.NickName, username, msg.Content)
	log.Printf("userid : %v", userid)

	cozeHandle(msg)
	allocateGroupHandle(msg, group)

	if group.NickName != "私斋蒸鹅心" {
		return nil
	}

	for _, value := range globalmap.DisableMemberNickNameArr {
		if username == value {
			fmt.Println("过滤用户:", value)
			return nil
		}
	}
	currentTime := time.Now()
	nineAM := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 9, 0, 0, 0, currentTime.Location())
	sixPM := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 18, 0, 0, 0, currentTime.Location())
	if msg.IsComeFromGroup() && currentTime.After(nineAM) && currentTime.Before(sixPM) {
		switch group.NickName {
		case "私斋蒸鹅心":
			//消息统计功能
			if val, exists2 := globalmap.Group2SpeakCountMap[username]; exists2 {
				globalmap.Group2SpeakCountMap[username] = val + 1
			} else {
				globalmap.Group2SpeakCountMap[username] = 1
			}

			if val, exists := globalmap.GlobalMap[username]; exists {
				// 键存在，增加值
				globalmap.GlobalMap[username] = val + 1
			} else {
				// 键不存在，可以选择进行处理，例如初始化为1
				globalmap.GlobalMap[username] = 1
			}
			//当前排名输出功能
			if msg.Content == "当前排名" {
				msg.ReplyText(getMessageContent())
			}
			if msg.Content == "工资" {
				msg.ReplyText(getSortSalary())
			}
			break
		case "🀄兩吋的好朋友":
			if val, exists := globalmap.Group1SpeakCountMap[username]; exists {
				// 键存在，增加值
				globalmap.Group1SpeakCountMap[username] = val + 1
			} else {
				// 键不存在，可以选择进行处理，例如初始化为1
				globalmap.Group1SpeakCountMap[username] = 1
			}
			break
		}
	} else {
		globalmap.GlobalMap = make(map[string]int)
		globalmap.Group1SpeakCountMap = make(map[string]int)
		globalmap.Group2SpeakCountMap = make(map[string]int)
		return nil
	}
	fmt.Println(globalmap.GlobalMap)
	fmt.Println(globalmap.Group1SpeakCountMap)
	fmt.Println(globalmap.Group2SpeakCountMap)

	// if username == "老大叔" {
	// msg.ReplyText("阿叶我是你爹")
	// }

	// 回复@我的用户
	// reply = strings.TrimSpace(reply)
	// reply = strings.Trim(reply, "\n")
	// atText := "@" + groupSender.NickName
	// replyText := atText + reply
	// _, err = msg.ReplyText(replyText)
	// if err != nil {
	// 	log.Printf("response group error: %v \n", err)
	// }
	return err
}

func allocateGroupHandle(msg *openwechat.Message, group openwechat.Group) {
	if strings.Contains(group.NickName, "肆零肆") {
		if msg.IsJoinGroup() {
			msg.ReplyText("新朋友请仔细阅读群公告，私加好友前需要询问是否同意，祝玩得开心～")
		}
	}
}

func cozeHandle(msg *openwechat.Message) {
	log.Printf("coze请求:", msg)
	sender, _ := msg.Sender()
	log.Printf("是否为@消息:", msg.IsAt())
	group := openwechat.Group{User: sender}
	// self, _ := msg.Bot().GetCurrentUser()
	if !msg.IsAt() {
		log.Printf("return")
		return
	}

	groupSender, _ := msg.SenderInGroup()
	conversationKey := group.NickName + "#" + groupSender.NickName
	value, exists := globalmap.GroupToConversationIdMap[conversationKey]
	if strings.Contains(msg.Content, "clearAll") {
		globalmap.MemberToChatHistories = make(map[string][]globalmap.ChatHistory)
		log.Printf("all聊天记录:%v", globalmap.MemberToChatHistories)
		return
	}
	if strings.Contains(msg.Content, "clear") {
		globalmap.GroupToConversationIdMap[conversationKey] = globalmap.GroupToConversationIdMap[conversationKey] + 1
		globalmap.MemberToChatHistories[conversationKey] = []globalmap.ChatHistory{}
		log.Printf("conversationKey聊天记录:%v", globalmap.MemberToChatHistories[conversationKey])
		return
	}

	if !exists {
		globalmap.GroupToConversationIdMap[conversationKey] = 1
		value = globalmap.GroupToConversationIdMap[conversationKey]
	}

	atText := "@" + groupSender.NickName + " "

	url := "https://api.coze.cn/open_api/v2/chat"
	token := "pat_0Zy3u5D1SEEaVIDXNNQavC74xIDmB7jnK3Di3PqkiIteHLQ4TlVv6nOfKPwXPikq"
	params := globalmap.RequestParams{
		BotID:          "7379431475772833818",
		User:           groupSender.NickName,
		Query:          msg.Content,
		ConversationID: conversationKey + strconv.Itoa(value),
		Histories:      globalmap.MemberToChatHistories[conversationKey], // 可以添加实际的历史记录
	}
	// botID := ""
	// user :=
	// query :=
	stream := false
	log.Printf("当前上下文ID:", params.ConversationID)

	response, err := sendPostRequest(url, token, params, stream)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	str1 := ""
	addChatHistory("user", str1, msg.Content, "text", conversationKey)

	content, err := extractFirstAnswerContent(response)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	addChatHistory("assistant", "answer", content, "text", conversationKey)
	msg.ReplyText(atText + content)

	fmt.Println("First Answer Content:", content)
}

func addChatHistory(role, typ, content, contentType, conversationKey string) {
	newChatHistory := globalmap.ChatHistory{
		Role:        role,
		Type:        typ,
		Content:     content,
		ContentType: contentType,
	}
	chatHistories, existsChatHistories := globalmap.MemberToChatHistories[conversationKey]
	if !existsChatHistories {
		globalmap.MemberToChatHistories[conversationKey] = make([]globalmap.ChatHistory, 0)
		globalmap.MemberToChatHistories[conversationKey] = append(globalmap.MemberToChatHistories[conversationKey], newChatHistory)
		log.Printf("conversationKey:%v,ChatHistories:%v", conversationKey, globalmap.MemberToChatHistories[conversationKey])
		return
	}
	chatHistories = append(chatHistories, newChatHistory)
	globalmap.MemberToChatHistories[conversationKey] = chatHistories
	// globalmap.ChatHistories = append(globalmap.ChatHistories, newChatHistory)
	log.Printf("conversationKey:%v,ChatHistories:%v", conversationKey, globalmap.MemberToChatHistories[conversationKey])
}

// sendPostRequest 发送POST请求并解析响应
func sendPostRequest(url, token string, params globalmap.RequestParams, stream bool) (string, error) {
	log.Printf("开始请求:url:%v , token:%v,params:%v,stream:%v", url, token, params, stream)
	// 构建请求体
	requestBody, err := json.Marshal(map[string]interface{}{
		"bot_id":          params.BotID,
		"user":            params.User,
		"query":           params.Query,
		"conversation_id": params.ConversationID,
		"chat_history":    params.Histories,
		"stream":          stream,
	})
	if err != nil {
		return "", fmt.Errorf("error marshalling request body: %v", err)
	}
	fmt.Println("请求体:" + string(requestBody))
	// 创建POST请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
	if err != nil {
		return "", fmt.Errorf("error creating request: %v", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+token)

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("error sending request: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("error reading response body: %v", err)
	}

	return string(body), nil
}

// extractFirstAnswerContent 从响应中提取第一条type为answer的content
func extractFirstAnswerContent(response string) (string, error) {
	fmt.Println("response:", response)
	var jsonResponse map[string]interface{}
	err := json.Unmarshal([]byte(response), &jsonResponse)
	if err != nil {
		return "", fmt.Errorf("error unmarshalling response: %v", err)
	}

	messages, ok := jsonResponse["messages"].([]interface{})
	if !ok {
		return "", fmt.Errorf("messages key not found or is not an array")
	}

	for _, msg := range messages {
		messageMap, ok := msg.(map[string]interface{})
		if !ok {
			continue
		}

		if messageMap["type"] == "answer" {
			content, ok := messageMap["content"].(string)
			if ok {
				return content, nil
			}
		}
	}

	return "", fmt.Errorf("no content with type 'answer' found")
}

func getMessageContent() string {
	currentTime := time.Now()

	formattedTime := currentTime.Format("2006-01-02 15:04:05")
	fmt.Println("Formatted Time:", formattedTime)
	result := ""
	// var values []int
	// for _, v := range globalmap {
	// values = append(values, v)
	// }
	// 对切片进行排序
	// sort.Ints(values)
	var startTime = time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), currentTime.Hour(), 0, 0, 0, currentTime.Location())
	startFormattedTime := startTime.Format("2006-01-02 15:04:05")
	type userKPI struct {
		key   string
		value int
	}
	var lstUserKPI []userKPI
	for k, v := range globalmap.GlobalMap {
		lstUserKPI = append(lstUserKPI, userKPI{k, v})
	}
	if len(lstUserKPI) == 0 {
		return result
	}
	sort.Slice(lstUserKPI, func(i, j int) bool {
		return lstUserKPI[i].value > lstUserKPI[j].value // 降序
	})

	for i := 0; i < len(lstUserKPI); i++ {
		// days := covertDays(value)
		fmt.Println("result:", result)
		var topThreeIcon = ""
		switch i {
		case 0:
			topThreeIcon = "🥇"
		case 1:
			topThreeIcon = "🥈"
		case 2:
			topThreeIcon = "🥉"
		default:
			topThreeIcon = "用户："
		}
		result = result + "\n" + topThreeIcon + fmt.Sprint(lstUserKPI[i].key) + "\n 时间：" + startFormattedTime + " - " + formattedTime +
			"\n 摸鱼绩效汇总发言:" + fmt.Sprint(lstUserKPI[i].value) + "次\n"
	}
	for _, value := range globalmap.DisableMemberNickNameArr {
		result = result + "\n🤡：" + value + "\n"
	}

	return result
}

func getSortSalary() string {
	result := ""

	type memberSalary struct {
		key   string
		value string
	}

	var memberSalaries []memberSalary
	for k, v := range globalmap.MemberSalaryMap {
		memberSalaries = append(memberSalaries, memberSalary{k, v})
	}
	if len(memberSalaries) == 0 {
		return result
	}
	sort.Slice(memberSalaries, func(i, j int) bool {
		return memberSalaries[i].value > memberSalaries[j].value // 降序
	})

	for i := 0; i < len(memberSalaries); i++ {
		// days := covertDays(value)
		fmt.Println("result:", result)
		// var topThreeIcon = ""
		// switch i {
		// case 0:
		// 	topThreeIcon = "🥇"
		// case 1:
		// 	topThreeIcon = "🥈"
		// case 2:
		// 	topThreeIcon = "🥉"
		// default:
		// 	topThreeIcon = "🤡："
		// }
		result = result + "\n" + fmt.Sprint(memberSalaries[i].key) + ":  " + fmt.Sprint(memberSalaries[i].value)
	}
	return result
}
